﻿using System;
using System.Globalization;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Markup;
using System.Windows.Media.Imaging;

namespace MediaBrowser.Gui.Converters
{
    /// <summary>
    /// Cette classe convertit une valeur String en un Contrôle Image. 
    /// </summary>
    [ValueConversion(typeof(String), typeof(Image))]
    public class StringToImageConverter : MarkupExtension, IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            String urlImg = value as String;
            try
            {
                Image img = new Image();
                //BitmapImage b = new BitmapImage(new Uri(urlImg));
                BitmapImage b = new BitmapImage();
                b.BeginInit();
                b.CacheOption = BitmapCacheOption.OnLoad;
                b.UriSource = new Uri(urlImg);
                b.EndInit();
                img.Source = b;
                img.Stretch = System.Windows.Media.Stretch.Fill;
                return img;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Image img = value as Image;
            return img.Source.ToString();
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return new StringToImageConverter();
        }

    }
}
